package com.erp.shop.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
import com.erp.shop.domain.dto.ErpSellerStoreSelfEvaluationDto;
import com.erp.shop.domain.bo.ErpSellerStoreEmpowerBo;
import com.erp.shop.service.IErpSellerStoreEmpowerService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.order.api.RemoteErpOrderService;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.vo.ErpSellerStoreEmpowerVo;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 卖家店铺授权
 *
 * @author erp
 * @date 2023-03-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/seller/sellerStoreEmpower")
public class ErpSellerStoreEmpowerController extends BaseController {

	private final IErpSellerStoreEmpowerService iErpSellerStoreEmpowerService;
	private final RemoteErpOrderService remoteErpOrderService;

    /**
     * 获取自运营店铺的真实利润和刷单利润
     */
    @GetMapping("/getSelfOperationEvaluation")
    public TableDataInfo<ErpSellerStoreSelfEvaluationDto> getSelfOperationEvaluation(PageQuery page, ErpSellerStoreSelfEvaluationDto dto) {
        return iErpSellerStoreEmpowerService.getSelfOperationEvaluation(page,dto);
    }

    /**
     * 根据storeUserName查询storeId
     */
    @PostMapping("/getIdByStoreUserName")
    public R<Object> getIdByStoreUserName(@RequestBody String jsonString) {
        JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class);
        String storeUserName = jsonObject.getString("storeUserName");
        ErpSellerStoreEmpower storeEmpower = iErpSellerStoreEmpowerService.selectEmpowerByUserName(storeUserName);
        if (storeEmpower == null) {
            return R.fail("未找到授权店铺");
        }
        return R.ok(storeEmpower);
    }

	/**
	 * 根据storeUserName查询有效授权店铺绑定信息
	 */
	@GetMapping("/getSellerStoreEmpowerByCnCode/{sellerLoginId}")
	public R<Object> getSellerStoreEmpowerByCnCode(@PathVariable("sellerLoginId") String sellerLoginId) {
		ErpSellerStoreEmpower storeEmpower = iErpSellerStoreEmpowerService.selectEmpowerByUserName(sellerLoginId);
		if (storeEmpower == null) {
			return R.fail("未找到授权店铺");
		}
		return R.ok(storeEmpower);
	}

	/**
	 * 根据storeUserName查询所有授权店铺绑定信息（含删除的）
	 */
	@GetMapping("/getStoreEmpowerListByCnCode/{sellerLoginId}")
	public R<Object> getStoreEmpowerListByCnCode(@PathVariable("sellerLoginId") String sellerLoginId) {
		List<ErpSellerStoreEmpower> storeEmpowerList = iErpSellerStoreEmpowerService.selectListByStoreUserName(sellerLoginId);
		if (storeEmpowerList == null || storeEmpowerList.size() == 0) {
			return R.fail("未找到授权店铺");
		}
		return R.ok(storeEmpowerList);
	}

	/**
	 * 根据店铺ID，查询店铺绑定信息
	 * @param storeId
	 * @return
	 */
	@GetMapping("/getSellerStoreEmpowerByStoreId/{storeId}")
	public R<Object> getSellerStoreEmpowerByStoreId(@PathVariable("storeId") String storeId){
		ErpSellerStoreEmpower storeEmpower = iErpSellerStoreEmpowerService.queryByStoreId(Long.parseLong(storeId));
		if (storeEmpower == null) {
			return R.fail("未找到授权店铺");
		}
		return R.ok(storeEmpower);
	}

	@GetMapping("/getAutoStoreInfo")
	public List<ErpSellerStoreEmpower> getAutoStoreInfo() {
//        Long userId = LoginHelper.getUserId();
		return iErpSellerStoreEmpowerService.getAutoStoreInfo();
	}

	/**
	 * 卖家全名选择框(未加权限)
	 */
	@GetMapping("/getUserStore")
	public R<Object> getUserStore() {
		List<ErpSellerStoreEmpower> list = iErpSellerStoreEmpowerService.getAllStoreEmpower();
		List<Map<String, Object>> reslist = new ArrayList<>();
		Map<String, Object> map = null;
		for (ErpSellerStoreEmpower vo : list) {
			map = new HashMap<>();
			map.put("storeName", vo.getStoreName());
			map.put("storeUserName", vo.getStoreUserName());
			map.put("value", vo.getId());
			reslist.add(map);
		}
		return R.ok(reslist);
	}

    /**
     * 添加测评  店铺列表
     * @return
     */
	@GetMapping("/getSellerSignerFullname")
	public R<Object> getSellerSignerFullname() {
		List<ErpSellerStoreEmpower> list = iErpSellerStoreEmpowerService.getAllStoreEmpower();
		List<Map<String, Object>> reslist = new ArrayList<>();
		Map<String, Object> map = null;
		for (ErpSellerStoreEmpower vo : list) {
			String storeUserName = vo.getStoreUserName();
			// 去订单表里找
            R<Object> objectR = remoteErpOrderService.getNewestOrderByStoreUserName(storeUserName);
            if (objectR.getCode() != 200) {
                continue;
            }
            ErpSellerOrder order = JSONObject.parseObject(JSONObject.toJSONString(objectR.getData()), ErpSellerOrder.class);
            String label = vo.getStoreName();
			if (order != null) {
				label = order.getSellerSignerFullname() + " " + label;
			}
			map = new HashMap<>();
			map.put("label", label);
			map.put("value", vo.getId());
			reslist.add(map);
		}
		return R.ok(reslist);
	}

	/**
	 * 店铺选择框列表
	 *
	 * @return
	 */
	@GetMapping("/selectList")
	public R<Object> selectList(ErpSellerStoreEmpowerBo bo) {
		List<ErpSellerStoreEmpowerVo> list = iErpSellerStoreEmpowerService.queryList(bo);
		List<Map<String, Object>> reslist = new ArrayList<>();
		Map<String, Object> map = null;
		for (ErpSellerStoreEmpowerVo vo : list) {
			map = new HashMap<>();
			map.put("lable", vo.getStoreName());
            map.put("storeUserName", vo.getStoreUserName());
			map.put("value", vo.getId());
			reslist.add(map);
		}
		return R.ok(reslist);
	}

	/**
	 * 查询卖家店铺授权列表
	 */
	@SaCheckPermission("seller:sellerStoreEmpower:list")
	@GetMapping("/list")
	public TableDataInfo<ErpSellerStoreEmpowerVo> list(ErpSellerStoreEmpowerBo bo, PageQuery pageQuery) {
		return iErpSellerStoreEmpowerService.queryPageList(bo, pageQuery);
	}

	/**
	 * 导出卖家店铺授权列表
	 */
	@SaCheckPermission("seller:sellerStoreEmpower:export")
	@Log(title = "卖家店铺授权", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(ErpSellerStoreEmpowerBo bo, HttpServletResponse response) {
		List<ErpSellerStoreEmpowerVo> list = iErpSellerStoreEmpowerService.queryList(bo);
//		ExcelUtil.exportExcel(list, "卖家店铺授权", ErpSellerStoreEmpowerVo.class, response);
	}

	/**
	 * 获取卖家店铺授权详细信息
	 *
	 * @param id 主键
	 */
	@SaCheckPermission("seller:sellerStoreEmpower:query")
	@GetMapping("/{id}")
	public R<ErpSellerStoreEmpowerVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
		return R.ok(iErpSellerStoreEmpowerService.queryById(id));
	}
    @GetMapping("/getCompriseDeleteById")
    public ErpSellerStoreEmpower getCompriseDeleteById(@RequestParam("id") Long id) {
        if (id == null) {
            return null;
        }
        return iErpSellerStoreEmpowerService.getCompriseDeleteById(id);
    }

	/**
	 * 新增卖家店铺授权
	 */
	@SaCheckPermission("seller:sellerStoreEmpower:add")
	@Log(title = "卖家店铺授权", businessType = BusinessType.INSERT)
	@RepeatSubmit()
	@PostMapping()
	public R<Void> add(@Validated(AddGroup.class) @RequestBody ErpSellerStoreEmpowerBo bo) {
		return toAjax(iErpSellerStoreEmpowerService.insertByBo(bo));
	}

    /**
     * 新增绑定
     */
    @RepeatSubmit()
    @PostMapping("/bindShop")
    public R<Object> bindShop(@RequestBody ErpSellerStoreEmpowerBo bo) {
        return iErpSellerStoreEmpowerService.bindShop(bo);
    }

    /**
     * 解绑
     */
    @GetMapping("unbindShop")
    public R<Object> unbindShop(String storeUserName) {
        return iErpSellerStoreEmpowerService.unbindShop(storeUserName);
    }

    /**
	 * 修改卖家店铺授权
	 */
	@SaCheckPermission("seller:sellerStoreEmpower:edit")
	@Log(title = "卖家店铺授权", businessType = BusinessType.UPDATE)
	@RepeatSubmit()
	@PutMapping()
	public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpSellerStoreEmpowerBo bo) {
		return toAjax(iErpSellerStoreEmpowerService.updateByBo(bo));
	}

	/**
	 * 删除卖家店铺授权
	 *
	 * @param ids 主键串
	 */
	@SaCheckPermission("seller:sellerStoreEmpower:remove")
	@Log(title = "卖家店铺授权", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
		return toAjax(iErpSellerStoreEmpowerService.deleteWithValidByIds(Arrays.asList(ids), true));
	}

	/**
	 * 查看是否有过期店铺
	 *
	 * @param bo
	 * @return
	 */
	@GetMapping("/ckeckEmpowerStatus")
	public R<Object> ckeckEmpowerStatus(ErpSellerStoreEmpowerBo bo) {
		List<ErpSellerStoreEmpowerVo> list = iErpSellerStoreEmpowerService.queryList(bo);

		int i = 0;
		for (ErpSellerStoreEmpowerVo vo : list) {
			Date expireTime = vo.getExpireTime();
			// 判断是否过期
			if (expireTime != null) {
				if (expireTime.before(new Date())) {
					i++;
				}
			}
		}

		if (i == 0) {
			return R.ok("","");
		} else {
			return R.ok("","您有" + i + "个店铺已过期，请重新登陆！");
		}
	}

	/**
	 * 更改密码
	 * @return
	 */
	@GetMapping("/updateStorePassWord")
	public R<Object> updateStorePassWord(String storeUserName, String storePassWord) {
		if (iErpSellerStoreEmpowerService.updateStorePassWord(storeUserName,storePassWord)){
			return R.ok("修改店铺密码成功");
		}else {
			return R.fail("更改密码失败");
		}
	}

	@GetMapping("/storeDiagnosis")
	public R<Object> storeDiagnosis(Long storeId) {
		return iErpSellerStoreEmpowerService.storeDiagnosis(storeId);
	}

	@GetMapping("/getEmpowerStore")
	public R<Object> getEmpowerStore() {
        List<ErpSellerStoreEmpower> empowerStore = iErpSellerStoreEmpowerService.getEmpowerStore();
        return R.ok(empowerStore);
	}

	@PostMapping("/getSellerStoreListByInfo")
	public R<Object> getSellerStoreListByInfo(@RequestBody ErpSellerStoreEmpower storeEmpower) {
        return iErpSellerStoreEmpowerService.getSellerStoreListByInfo(storeEmpower);
	}

	@PostMapping("/selectEmpowerInUserName")
	public R<Object> selectEmpowerInUserName(@RequestBody List<String> collect) {
        return iErpSellerStoreEmpowerService.selectEmpowerInUserName(collect);
	}


}
